package jmp3player;

import java.awt.Color;
import java.io.File;
import javax.swing.DefaultListModel;
import org.jdesktop.application.Action;
import java.util.*;
import static java.util.Collections.*;

/**
 * Klasa wyświetlająca okno dialogowe wyboru plików
 * @author lukeh
 * @version 1.0
 */
public class openDlg extends javax.swing.JDialog
  {

    /**
     * Tworzy nowe okno do otwarcia plików.
     * Pozwala na wybór folderów, jeśli ext = ""
     * lub plików o rozszerzeniu takim jak ext
     * Poprzez parametr ext zwracana jest ścieżka dostępu do wybranego pliku
     * @param parent - uchwyt okna nadrzędnego
     * @param ext - rozszerzenie pliku i wartość zwrotna
     */
    public openDlg(java.awt.Frame parent, StringBuffer ext)
        {
        super(parent);

        initComponents();
        this.parent = parent;
        this.ext = ext;
        getRootPane().setDefaultButton(Otworz);
        plik = new File(".");
        //String addr = plik.getAbsolutePath();
        String addr;

        addr = plik.getAbsolutePath();
        addr = addr.substring(0, addr.length() - 1);
        plik = new File(addr);
        Adres.setText(addr);


        openFile();


        }

    /**
     * Wypełnia listę zawartością aktualnego folderu.
     * Najpierw foldery, późńiej, jeśli wskazano rozszerzenie, pliki
     */
    @Action
    public void openFile()
        {

        try
            {
            model.clear();
            //if(Adres.getText().getBytes()[Adres.getText().length()-1]!='/')Adres.setText(Adres.getText()+"/");
            // plik = new File(Adres.getText());

            String[] pliki = plik.list();

            Vector<String> v = new Vector<String>();
            addAll(v, pliki);
            sort(v);
            for (String s : v)
                {
                //System.out.println(s);
                if (new File(Adres.getText() + "/" + s).isDirectory())
                    {
                    model.add(model.size(), s);
                    Lista.getComponent(0).setBackground(new Color(0, 0, 1));
                    }
                }
            if (ext.length() != 0)
                {
                System.out.print("weszło");
                for (String s : v)
                    {
                    if (s.endsWith(ext.toString()))
                        {
                        model.add(model.size(), s);
                        }
                    }
                }
            currentAddr = Adres.getText();
            } catch (Exception e)
            {
            Adres.setText(currentAddr);
            openAddr();
            }
        }

    /**
     * Przechodzi w górę w strukturze katalogów
     */
    @Action
    public void dirUp()
        {
        // System.out.println(plik.getAbsolutePath());
        plik = plik.getParentFile();
        if (plik != null)
            {
            String addr = plik.getPath();

            Adres.setText(addr);
            // plik = new File(addr);
            openFile();
            }

        }

    /**
     * Zatwierdza wybór pliku/katalogu
     * Zamyka okno
     */
    @Action
    public void fileAck()
        {
        if (ext.length() == 0)
            {
            System.out.println("asa");
            ext.delete(0, ext.capacity());
            ext.append(plik.getPath());
            dispose();
            } else
            {
            if (plik.getName().endsWith(ext.toString()))
                {
                System.out.println(plik.getPath());
                ext.delete(0, ext.capacity());
                ext.append(plik.getPath());
                dispose();
                }
            }
        }

    /**
     * Otwiera adres ręcznie wpisany w pole adresu
     */
    @Action
    public void openAddr()
        {
        plik = new File(Adres.getText());
        openFile();
        }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
 
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        Otworz = new javax.swing.JButton();
        wGore = new javax.swing.JButton();
        OK = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        Lista = new javax.swing.JList();
        Adres = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(jmp3player.Jmp3PlayerApp.class).getContext().getResourceMap(openDlg.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setModal(true);
        setName("Form"); // NOI18N
        setResizable(false);

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(jmp3player.Jmp3PlayerApp.class).getContext().getActionMap(openDlg.class, this);
        Otworz.setAction(actionMap.get("openAddr")); // NOI18N
        Otworz.setText(resourceMap.getString("Otworz.text")); // NOI18N
        Otworz.setName("Otworz"); // NOI18N

        wGore.setAction(actionMap.get("dirUp")); // NOI18N
        wGore.setText(resourceMap.getString("wGore.text")); // NOI18N
        wGore.setName("wGore"); // NOI18N

        OK.setAction(actionMap.get("fileAck")); // NOI18N
        OK.setText(resourceMap.getString("OK.text")); // NOI18N
        OK.setName("OK"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        model = new DefaultListModel();
        Lista.setModel(model);
        Lista.setName("Lista"); // NOI18N
        Lista.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                klikLista(evt);
            }
        });
        jScrollPane1.setViewportView(Lista);

        Adres.setText(resourceMap.getString("Adres.text")); // NOI18N
        Adres.setName("Adres"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(OK, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(Adres, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(Otworz)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(wGore))
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 355, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Adres, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(Otworz)
                    .addComponent(wGore))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(OK, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
/*
 * Obsługa kliknięcia na pole w liście plików/folderów
 *
 */
    private void klikLista(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_klikLista
        String addr = plik.getPath();
        
        plik = new File(addr + "/" +model.getElementAt(Lista.getSelectedIndex()) );
        //addr = addr + model.getElementAt(Lista.getSelectedIndex()) + "/";



    if(plik.isDirectory())
    {
        addr = plik.getPath();
        Adres.setText(addr);
        openFile();
    }
    }//GEN-LAST:event_klikLista

    /**
    * @param args the command line arguments
    */
  
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField Adres;
    private javax.swing.JList Lista;
    private javax.swing.JButton OK;
    private javax.swing.JButton Otworz;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton wGore;
    // End of variables declaration//GEN-END:variables
    private File plik;
    /** Uchwyt pliku*/
    DefaultListModel model;
    /**Model listy plików/folderów*/
    String currentAddr;
    /**Aktualnie przetwarzany adres*/
    java.awt.Frame parent;
    /**Uchwyt okna nadrzędnego*/
    StringBuffer ext;
    /**Bufor na rozszerzenie/adres pliku*/
  }
